package com.scs.application.modules.settlement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.entity.Hospital;
import com.scs.application.modules.base.request.HospitalSupplierRequest;
import com.scs.application.modules.base.service.HospitalSupplierService;
import com.scs.application.modules.base.vo.HospitalSupplierVO;
import com.scs.application.modules.settlement.dto.StockPsiDTO;
import com.scs.application.modules.settlement.entity.StockPsi;
import com.scs.application.modules.settlement.mapper.StockPsiMapper;
import com.scs.application.modules.settlement.request.StockPsiQueryRequest;
import com.scs.application.modules.settlement.service.StockPsiService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 库存进销存数据 service 实现
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class StockPsiServiceImpl extends BaseServiceImpl<StockPsiMapper, StockPsi> implements StockPsiService {

    @Autowired
    private HospitalSupplierService hospitalSupplierService;

    @Override
    public List<StockPsi> list(StockPsiQueryRequest request) {
        List<StockPsi> list = this.list(getQueryWrapper(request));
        return list;
    }

    @Override
    public IPage<StockPsi> page(StockPsiQueryRequest request) {
        request.setSupplierId(UserUtils.getSupplierId());
        IPage page = this.page(request.getPage(), Wrappers.<StockPsi>query()
                .eq(StringUtils.isNotBlank(request.getSupplierId()), "supplier_id", request.getSupplierId())
                .eq(StringUtils.isNotBlank(request.getPeriod()), "period", request.getPeriod())
                .like(StringUtils.isNotBlank(request.getMaterialName()), "material_name", request.getMaterialName())
                .like(StringUtils.isNotBlank(request.getMaterialSpec()), "material_spec", request.getMaterialSpec())
        );
        return page;
    }

    private QueryWrapper<StockPsi> getQueryWrapper(StockPsiQueryRequest request){
        return Wrappers.<StockPsi>query()
                .orderByDesc("gmt_modified");
    }

    @Override
    public CommonResult saveStockPsi(@RequestBody List<StockPsiDTO> stockPsiDTOS) {
        if (stockPsiDTOS == null || stockPsiDTOS.isEmpty()) {
            return CommonResult.error("传入数据不能为空");
        }

        String msg = "保存成功";
        boolean flagCode = false;
        List<String> periods = stockPsiDTOS.parallelStream().map(StockPsiDTO::getPeriod).distinct().collect(Collectors.toList());
        Hospital hospital = UserUtils.getHospital();

        HospitalSupplierRequest hospitalSupplierRequest = new HospitalSupplierRequest();
        hospitalSupplierRequest.setHospitalId(hospital.getId());
        List<HospitalSupplierVO> hospitalSupplierVOS = hospitalSupplierService.listVO(hospitalSupplierRequest);
        List<StockPsi> stockPsiList = Lists.newArrayListWithCapacity(stockPsiDTOS.size());
        List<StockPsi> existsStockPsiList = this.list(Wrappers.<StockPsi>query().in("period", periods));
        for (StockPsiDTO dto: stockPsiDTOS) {
            StockPsi stockPsi = new StockPsi();
            BeanUtils.copyProperties(dto, stockPsi);
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(dto.getSupplierMSCMCode())){
                flagCode = true;
                continue;
            }
            stockPsi.setHospitalId(hospital.getId()).setHospitalName(hospital.getName());
            hospitalSupplierVOS.stream().filter(hsvo -> dto.getSupplierMSCMCode().equalsIgnoreCase(hsvo.getSupplierId())).findFirst().ifPresent( hsvo -> {
                stockPsi.setSupplierId(hsvo.getSupplierId()).setSupplierName(hsvo.getSupplierName());
            });
            existsStockPsiList.stream().filter(stockPsi1 -> dto.getPeriod().equalsIgnoreCase(stockPsi1.getPeriod())
                    && dto.getMaterialCode().equalsIgnoreCase(stockPsi1.getMaterialCode())).findFirst()
                    .ifPresent(stockPsi1 -> stockPsi.setId(stockPsi1.getId()));
            stockPsiList.add(stockPsi);
        }
        log.info("检测到{}条进销存数据,有{}条需要新增，有{}条需要更新", stockPsiDTOS.size(), stockPsiList.stream().filter(stockPsi -> com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(stockPsi.getId())).count(), stockPsiList.stream().filter(stockPsi -> com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(stockPsi.getId())).count());
        this.saveOrUpdateBatch(stockPsiList);
        if(flagCode){
            msg += ",你还有SupplierMscmCode为空的商品，请补全后推送！";
        }
        return CommonResult.ok(msg);
    }
}

